<template>
  <basic-dialog
    width="60%"
    :title="dialogTitle"
    :visible="visible"
    :showFooter="false"
    :showClose="false"
  >
    <basic-form
      ref="formData"
      formItemWidth="120px"
      defaultExpandStatus
      isBtnBarSingleRow
      :isScalingBtn="false"
      :hasQueryPermission="false"
      :formColumns="formItemList"
      :dataSource="formData"
      :handleSearchForm="handleQueryForm"
      @getFormData="updateFormData"
    >
      <el-row slot="extensionActions">
        <el-button v-if="isNotLinked()" type="primary" @click="handleBatchLink">批量关联</el-button>
        <el-button v-if="isLinked()" @click="handleBatchCancel">批量取消</el-button>
      </el-row>
    </basic-form>
    <el-tabs v-model="tabs.current" @tab-click="handleSwitchTabs">
      <el-tab-pane label="未关联" :name="tabs.nameList[0]"></el-tab-pane>
      <el-tab-pane label="已关联" :name="tabs.nameList[1]"></el-tab-pane>
    </el-tabs>
    <SkusTable
      showActionCol
      showPagination
      showSelectCol
      :dataSource="tableInfo.list"
      :columns="tableInfo.columns"
      :loading="tableInfo.loading"
      :total="pagination.total"
      :pageSizes="pageSizes"
      :pagination="pagination"
      :actionRender="renderTableBtnAction"
      :selectionChange="handleSelectionChange"
      @pageChange="handlePageChange"
      @pageSizeSelect="handlePageSizeChange"
    />
    <el-row class="dialog_footer" type="flex" justify="center">
      <template v-if="isShowCancel">
        <el-button type="primary" @click="handleEnsure">确定</el-button>
        <el-button @click="handleClose">取消</el-button>
      </template>
      <template v-else>
        <el-button type="primary" @click="handleEnsure">返回表单</el-button>
      </template>
    </el-row>
  </basic-dialog>
</template>
<script>
import { requestToData } from '@/api/commonHttp';
import BasicDialog from '@/components/BasicDialog';
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import { LinkGoods } from './LinkGoods';
import { skuFormItems, skuFormData } from './constants';
import { getTableAction } from '@/utils/getBtnsRender';
export default {
  components: {
    BasicDialog,
    BasicForm,
    SkusTable
  },
  props: {
    dialogTitle: { // 弹框名称
      type: String,
      default: '关联弹框'
    },
    visible: { // 弹框开关
      type: Boolean,
      default: false
    },
    goodsDimension: { // 商品维度，默认SKU
      type: String,
      default: 'sku'
    },
    linkDimension: { // 关联维度，默认skuNo
      type: String,
      default: 'skuNo'
    },
    newForms: { // 整个需要替换的form（包括formItemList和formData）
      type: Object
    },
    extraForms: { // 需要额外扩展表单字段的form项（包括formItemList和formData）
      type: Object,
      default () {
        return {
          formItemList: [],
          formData: {}
        }
      }
    },
    tableColumns: { // 关联表格的表列
      type: Array,
      default () {
        return [
          { title: '商品名称', key: 'productName' },
          { title: 'SPU编码', key: 'spuNo' },
          { title: '商品分类', key: 'categoryPath' },
          { title: 'SKU编码', key: 'skuNo' },
          { title: '规格参数', key: 'specDetailStr' },
          { title: '品牌', key: 'brandName' },
        ]
      }
    },
    pageSizes: { // 弹框分页页码
      type: Array,
      default () { return [10, 50, 100, 500, 1000]; }
    },
    queryUrl: { // 查询接口
      type: String,
      default: ''
    },
    queryType: { // 查询类别，默认post查询
      type: String,
      default: 'post'
    },
    isFormQuery: { // 是form查询，默认false
      type: Boolean,
      default: false
    },
    getSearchParams: { // 获取查询入参（可以不传）
      type: Function
    },
    isQueryInit: { // 打开弹框初始是否加载查询
      type: Boolean,
      default: false
    },
    isShowCancel: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      formData: {},
      formItemList: [],
      tabs: {
        current: 'notLinked', // 当前tabs页签
        nameList: ['notLinked', 'linked'] // tabs页签key集合
      },
      tableInfo: {
        list: [],
        columns: this.tableColumns,
        loading: false,
        selection: []
      },
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      LinkGoods: new LinkGoods(this.linkDimension),
    }
  },
  mounted () {
    this.loadInitDataInMounted();
  },
  watch: {
    visible (val) {
      if (val) { this.LinkGoods.initPrev(); }
      if (val && this.isQueryInit) { this.handleQueryForm(); }
    },
  },
  methods: {
    renderTableBtnAction (h, { row }) {
      const linkBtn = [{ label: '关联', method: this.handleLink }];
      const cancelBtn = [{ label: '取消', method: this.handleCancel }];
      const actionList = this.isNotLinked() ? linkBtn : cancelBtn;
      return getTableAction({ h, row, actionList });
    },
    // 是未关联
    isNotLinked () {
      return this.tabs.current === this.tabs.nameList[0];
    },
    // 是已关联
    isLinked () {
      return this.tabs.current === this.tabs.nameList[1];
    },
    // 表格勾选为空
    isNullSelection () {
      return this.tableInfo.selection?.length === 0;
    },
    // 表单查询
    handleQueryForm () {
      this.pagination.pageNum = 1;
      this.getTableDataBySearchForm();
    },
    // 表格数据勾选或勾选取消
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 改变页码
    handlePageChange (currentPage) {
      this.pagination.pageNum = currentPage;
      this.getTableDataBySearchForm(); // 重新加载表格数据
    },
    // 改变当前页条数大小
    handlePageSizeChange (pageSize) {
      this.pagination.pageSize = pageSize;
      this.getTableDataBySearchForm(); // 重新加载表格数据
    },
    // 切换tabs
    handleSwitchTabs () {
      this.getTableDataBySearchForm(); // 重新加载表格数据
    },
    // 批量关联
    handleBatchLink () {
      if (this.isNullSelection()) { return this.$message.warning('请勾选列表'); }
      this.LinkGoods.batchAdd(this.tableInfo.selection);
      this.$message.success('批量关联成功');
      this.getTableDataBySearchForm(); // 重新加载表格数据
    },
    // 批量取消
    handleBatchCancel () {
      if (this.isNullSelection()) { return this.$message.warning('请勾选列表'); }
      this.LinkGoods.batchDelete(this.tableInfo.selection);
      this.$message.success('批量取消成功');
      this.getTableDataBySearchForm(); // 重新加载表格数据
    },
    // 关联
    handleLink (row) {
      this.LinkGoods.add(row);
      this.$message.success('关联成功');
      this.getTableDataBySearchForm(); // 重新加载表格数据
    },
    // 取消
    handleCancel (row) {
      this.LinkGoods.delete(row);
      this.$message.success('取消成功');
      this.getTableDataBySearchForm(); // 重新加载表格数据
    },
    // 返回表单（确定）
    handleEnsure () {
      this.$emit('getLinkedRows', this.LinkGoods.getResult());
      this.$emit('update:visible', false);
      this.resetState();
    },
    // 取消
    handleClose () {
      this.LinkGoods.cancel();
      this.$emit('update:visible', false);
    },
    // 加载初始数据在mounted时期
    loadInitDataInMounted () {
      this.initFormItemList();
      this.initFormData();
    },
    // 初始化表单筛选项集合
    initFormItemList () {
      const { formItemList } = this.extraForms;
      const defaultItems = {
        sku: skuFormItems
      }
      this.formItemList = [...defaultItems[this.goodsDimension], ...formItemList];
    },
    // 初始化表单数据
    initFormData () {
      const { formData } = this.extraForms;
      const defaultData = {
        sku: skuFormData
      }
      this.formData = { ...defaultData[this.goodsDimension], ...formData };
    },
    // 更新表单数据
    updateFormData (data) {
      this.formData = data;
    },
    resetState () {
      this.tabs.current = 'notLinked';
      this.tableInfo.list = [];
      this.pagination = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    },
    // 获取表格查询条件
    getParamsBySearchForm () {
      const { pageNum, pageSize } = this.pagination;
      const defaultMethods = {
        // sku: getParamsBySku
      }
      const data = {
        formData: this.formData,
        formItemList: this.formItemList,
        tabState: this.tabs.current,
        linkGoods: this.LinkGoods.getCurrent()
      }
      if (this.getSearchParams) { // 如果有特殊的获取入参方法，优先执行
        return {
          ...this.getSearchParams(data),
          nowPage: pageNum,
          pageShow: pageSize
        };
      }
      return {
        ...defaultMethods[this.goodsDimension](data),
        nowPage: pageNum,
        pageShow: pageSize
      };
    },
    // 获取表格数据
    async getTableDataBySearchForm () {
      const retData = await requestToData({
        url: this.queryUrl,
        type: this.queryType,
        data: this.getParamsBySearchForm(),
        isFormData: this.isFormQuery
      }, () => { this.tableInfo.loading = true; }, () => { this.tableInfo.loading = false; });
      if (!retData) { return false; }
      this.tableInfo.list = retData?.results || [];
      this.pagination.total = retData.totalNum;
    }
  }
}
</script>
<style lang="less" scoped>
.dialog_footer {
  border-top: 1px solid #ccc;
  padding-top: 10px;
}
</style>
